package web.directories.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import domain.entities.*;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.springframework.beans.factory.annotation.Autowired;
import services.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Guillermo
 * Date: 26/10/12
 * Time: 12:53
 * To change this template use File | Settings | File Templates.
 */
@Namespace("/Directories/Equipment")
public class EquipmentController extends ActionSupport implements ModelDriven, ServletResponseAware, ServletRequestAware {


    private ProtocolCRUDService protocolCRUDService;
    private EquipmentTypeService equipmentTypeService;
    private CentroCRUDService centroCRUDService;
    private EquipmentcertificationService equipmentcertificationService;
    private List<Equipmentcertification> equipmentcertificationList = new ArrayList<Equipmentcertification>();
    private List<EquipmentType> equipmentTypes;
    private List<Centro> centroList;
    private Centro centro = new Centro();
    private boolean create;
    private Equipmentcertification equipmentcertification = new Equipmentcertification();
    private String iddownload;
    private Integer editableId;


    @Autowired
    public EquipmentController(ProtocolCRUDService protocolCRUDService, EquipmentTypeService equipmentTypeService,
                               CentroCRUDService centroCRUDService, EquipmentcertificationService equipmentcertificationService) {
        this.protocolCRUDService = protocolCRUDService;
        this.equipmentTypeService = equipmentTypeService;
        this.centroCRUDService = centroCRUDService;
        this.equipmentcertificationService = equipmentcertificationService;
    }


    @Override
    public Object getModel() {
        return equipmentcertification;
    }

    @Action(value="main", results={
        @Result(name="success",location="/directories.equipment.tiles", type="tiles")
    })
    public String execute() {
        equipmentTypes = equipmentTypeService.findAll();
        centroList = centroCRUDService.findAllSites();

        return SUCCESS;
    }


    @Action(value="list", results={
            @Result(name="success", location="/directories.equipment.tiles", type="tiles")
    })
    public String list() {
        equipmentTypes = equipmentTypeService.findAll();
        centroList = centroCRUDService.findAllSites();
        //equipmentcertificationList = equipmentcertificationService.findAll();

        CriteriaEquipmentcertification criteriaEquipmentcertification = new CriteriaEquipmentcertification(equipmentcertification);
        equipmentcertificationList = equipmentcertificationService.list(criteriaEquipmentcertification);
        return SUCCESS;
    }


    @Action(value="create", results={
            @Result(name="success",location="/directories.equipment.create.tiles", type="tiles")
    })
    public String create() {

        equipmentTypes = equipmentTypeService.findAll();
        centroList = centroCRUDService.findAllSites();
        if( editableId != null)
            equipmentcertification =     equipmentcertificationService.findbyId( editableId );

    /*    if( centro != null && centro.getId() != null){
            equipmentcertificationList = equipmentcertificationService.findByCentroId( centro.getId());
            //cantEquipment = ((Integer)equipmentcertificationList.size()).toString();
            create = false;
        }else{
            create = true;
            equipmentcertificationList.add(new Equipmentcertification());
         //   cantEquipment = "1";
        }
       // ultimoIdEquipment = cantEquipment;          */
        return SUCCESS;
    }


    @Action(value="save", results={
            @Result(name="success",location="main", type="redirectAction")
    })
    public String save() throws IOException {

        /**
         *  modificado para que solo guarde de un equipment
         */

        if( equipmentcertification.getId() != null ){
            Equipmentcertification equipmentcertification1 = equipmentcertificationService.findbyId(equipmentcertification.getId());
            equipmentcertification.setFile(equipmentcertification1.getFile());
            equipmentcertification.setFilename(equipmentcertification1.getFilename());
        }

        equipmentcertification.setCentro((Centro) centroCRUDService.findById(equipmentcertification.getCentro().getId()));
        equipmentcertification.setEquipmentType(equipmentTypeService.findbyId(equipmentcertification.getEquipmentType().getId()));
        if(  equipmentcertification.getCertificationFileFileName() != null &&  !equipmentcertification.getCertificationFileFileName().equals("") )
            equipmentcertification.setCertification( equipmentcertification.getCertificationFileFileName() );

        if(equipmentcertification.getCertificationFile() != null ){
            FileInputStream fis;
            byte[] content = null;
            fis = new FileInputStream(equipmentcertification.getCertificationFile());
            content = new byte[fis.available()];
            fis.read(content);
            fis.close();

            equipmentcertification.setFile(content);
            equipmentcertification.setFilename(equipmentcertification.getCertificationFileFileName());
        }
        equipmentcertificationService.save(equipmentcertification);




    /*     centro = (Centro) centroCRUDService.findById(centro.getId());
        //recupero los adjuntos, no es la mejor forma.. pero bue.. una mancha mas..
        for (Equipmentcertification equipmentcertification : equipmentcertificationList){
            if( equipmentcertification.getId() != null ){
                Equipmentcertification equipmentcertification1 = equipmentcertificationService.findbyId(equipmentcertification.getId());
                equipmentcertification.setFile(equipmentcertification1.getFile());
                equipmentcertification.setFilename(equipmentcertification1.getFilename());
            }
        }

        if( !create )
            equipmentcertificationService.deleteByCentroId(centro.getId());
        for (Equipmentcertification equipmentcertification : equipmentcertificationList){
            equipmentcertification.setCentro(centro);
            equipmentcertification.setEquipmentType(equipmentTypeService.findbyId(equipmentcertification.getEquipmentType().getId()));
            if(  equipmentcertification.getCertificationFileFileName() != null &&  !equipmentcertification.getCertificationFileFileName().equals("") )
                equipmentcertification.setCertification( equipmentcertification.getCertificationFileFileName() );

            if(equipmentcertification.getCertificationFile() != null ){
                FileInputStream fis;
                byte[] content = null;
                fis = new FileInputStream(equipmentcertification.getCertificationFile());
                content = new byte[fis.available()];
                fis.read(content);
                fis.close();

                equipmentcertification.setFile(content);
                equipmentcertification.setFilename(equipmentcertification.getCertificationFileFileName());
            }
            equipmentcertification.setId(null);
            equipmentcertificationService.save(equipmentcertification);

        }

          */

        return SUCCESS;
    }


    @Action(value="downloadFile", results={
            @Result(name="success",location="/directories.equipment.create.tiles", type="tiles")
    })
    public String downloadFile() throws IOException {

        if( iddownload != null && !iddownload.equals("")){
            Equipmentcertification eq =   equipmentcertificationService.findbyId(Integer.parseInt(iddownload));

            if( eq.getFile() != null){
                String[] ext = eq.getFilename().split("\\.");
                // Initialize response.
                response.reset();
                if( ext[1].equals("pdf"))
                    response.setContentType("application/pdf");
                else
                    response.setContentType("application/doc");
                response.setHeader("Content-disposition", "attachment; filename=\""+eq.getFilename()+"\"");
                // Write file to response.
                OutputStream output = response.getOutputStream();
                output.write(eq.getFile());
                output.close();
            }
        }
        return SUCCESS;
    }


    public List<EquipmentType> getEquipmentTypes() {
        return equipmentTypes;
    }

    public void setEquipmentTypes(List<EquipmentType> equipmentTypes) {
        this.equipmentTypes = equipmentTypes;
    }

    public List<Centro> getCentroList() {
        return centroList;
    }

    public void setCentroList(List<Centro> centroList) {
        this.centroList = centroList;
    }

    public List<Equipmentcertification> getEquipmentcertificationList() {
        return equipmentcertificationList;
    }

    public void setEquipmentcertificationList(List<Equipmentcertification> equipmentcertificationList) {
        this.equipmentcertificationList = equipmentcertificationList;
    }

    public Centro getCentro() {
        return centro;
    }

    public void setCentro(Centro centro) {
        this.centro = centro;
    }


    public boolean isCreate() {
        return create;
    }

    public void setCreate(boolean create) {
        this.create = create;
    }

    public Equipmentcertification getEquipmentcertification() {
        return equipmentcertification;
    }

    public void setEquipmentcertification(Equipmentcertification equipmentcertification) {
        this.equipmentcertification = equipmentcertification;
    }

    public String getIddownload() {
        return iddownload;
    }

    public void setIddownload(String iddownload) {
        this.iddownload = iddownload;
    }

    private HttpServletRequest request;
    private HttpServletResponse response;

    @Override
    public void setServletRequest(javax.servlet.http.HttpServletRequest request) {
        this.request   = request;
    }

    @Override
    public void setServletResponse(javax.servlet.http.HttpServletResponse response) {
        this.response = response;
    }

    public Integer getEditableId() {
        return editableId;
    }

    public void setEditableId(Integer editableId) {
        this.editableId = editableId;
    }
}
